<?php

namespace app\index\controller;

use think\Controller;
use think\Request;

class Message extends IndexController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return view('index/message');
    }

    public function create()
    {
        $data = request()->post();
        $data['time'] = time();
        if( $data['bid'] == ''){
            $this->error('请填写接收人');
        }elseif($data['title'] == ''){
            $this->error('请设置好你的标题');
        }elseif($data['session'] == ''){
            $this->error('请填写上你的内容');
        }


        if($data['bid'] == 'ALLUSER') {
            //查找所有发送用户
            $bus_id = DB('business')
                ->field('id')
                ->select();

            unset($data['bid']);
            //接受消息,插入到message表中

            $list = DB('message')
                ->insertGetId($data);

            foreach ($bus_id as $k => $v){
                $bid['bid'] = $v['id'];
                $bid['sid'] = $list;
                $bus = DB('mes_bus')
                    ->insert($bid);
            }

            $this->success('消息发送成功');

        }elseif($data['bid'] == 'STOPUSER'){

                //查找所有禁用用户
                $bus_id = DB('business')
                    ->field('id')
                    ->where('status=0')
                    ->select();

                unset($data['bid']);
                //接受消息,插入到message表中

                $list = DB('message')
                    ->insertGetId($data);

                foreach ($bus_id as $k => $v){
                    $bid['bid'] = $v['id'];
                    $bid['sid'] = $list;
                    $bus = DB('mes_bus')
                        ->insert($bid);
                }

                $this->success('消息发送成功');

        }else{

            if(preg_match('/;{2,}|[^\d;]/',$data['bid'])){
                $this->error('你的ID格式有误');
            }

             $bus_id = explode(';',$data['bid']);
             unset($data['bid']);

             $list = DB('message')
                 ->insertGetId($data);

             foreach($bus_id as $k => $v){
                $bid['bid'] = $v;
                $bid['sid'] = $list;
                $bus = DB('mes_bus')
                    ->insert($bid);
            }

            $this->success('消息发送成功');
        }
    }

    public function read()
    {
        $list = DB('message')
            ->field('*')
            ->paginate(5);
        return view('index/mes_read',[
            'list'=>$list
        ]);
    }
}